﻿using System;
using System.IO;
using System.Net;
using System.Xml.Linq;
using TickSharp.Core.Exceptions;
using TickSharp.Core.Interfaces;

namespace TickSharp.Core.Infrastructure
{
    public class RepositoryBase
    {
        private readonly IApiConnectionInfo _apiConnectionInfo;

        public RepositoryBase(IApiConnectionInfo apiConnectionInfo)
        {
            _apiConnectionInfo = apiConnectionInfo;
        }

        protected string BuildUrl(string apiMethod, string additionalParams)
        {
            return string.Format("https://{0}/api/{1}?{2}&{3}", _apiConnectionInfo.ProjectDomain, apiMethod, _apiConnectionInfo.AuthenticationQueryString(), additionalParams);
        }

        protected XElement GetResponse(string uri)
        {
            var request = WebRequest.Create(uri) as HttpWebRequest;
            request.UserAgent = ".NET Sample";
            request.KeepAlive = false;

            request.Timeout = 15 * 1000;

            HttpWebResponse response;
            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException)
            {
                throw new TickspotAuthorizationException();
            }
            
            if (request.HaveResponse && response != null)
            {                
                var reader = new StreamReader(response.GetResponseStream());
                return XElement.Parse(reader.ReadToEnd());
            }
            throw new Exception("Error fetching data.");
        }
    }
}